﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SqlClient;

namespace MyVideoViewerServerSetup
{
    class Program
    {
        const string CONFIG_FOLDER_NAME = @"MyVideoViewer";
        static string myMoviesConnectionString = @"Data Source=localhost\MYMOVIES;Persist Security Info=True;User ID=sa;Password=t9AranuHA7";
        static string localConnectionString = @"Data Source=localhost\SQLEXPRESS;Integrated Security=True";
        static string connString;
        static SqlConnection conn;

        static void Main(string[] args)
        {   
            

            conn = new SqlConnection(myMoviesConnectionString);
            SqlCommand cmd = new SqlCommand("select count(*) from sys.databases where name = 'My Movies'", conn);

            Console.WriteLine("Checking for My Movies.");
            if (CheckDatabaseConnection())
            {
                connString = @"Data Source=localhost\MYMOVIES;Initial Catalog='MyVideoViewer';Persist Security Info=True;User ID=sa;Password=t9AranuHA7";
                SetupDatabase();
                return;
            }
            else
                Console.WriteLine("My Movies was not detected.");

            EmbeddedInstall EI = new EmbeddedInstall();

            conn = new SqlConnection(localConnectionString);
            connString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog='MyVideoViewer';Integrated Security=True";
            Console.WriteLine("Checking if database is already installed.");
            if (EI.IsExpressInstalled())
            {
                if (CheckDatabaseConnection())
                {
                    SetupDatabase();
                    return;
                }
                else
                    Console.WriteLine("A database was detected but was unable to connect to, please login as an administrator.");
            }

            Console.WriteLine("Attempting to install database.");
            EI.AutostartSQLBrowserService = true;
            EI.AutostartSQLService = true;
            EI.Collation = "SQL_Latin1_General_Cp1_CS_AS";
            EI.DisableNetworkProtocols = false;
            EI.InstanceName = "SQLEXPRESS";
            EI.ReportErrors = true;
            EI.SetupFileLocation = "sqlexpr.exe";  //Provide location for the Express setup file
            EI.SqlBrowserAccountName = ""; //Blank means LocalSystem
            EI.SqlBrowserPassword = ""; // N/A
            EI.SqlDataDirectory = "";
            EI.SqlInstallDirectory = "";
            EI.SqlInstallSharedDirectory = "";
            EI.SqlServiceAccountName = ""; //Blank means Localsystem
            EI.SqlServicePassword = ""; // N/A
            EI.SysadminPassword = "HuK2phun"; //<<Supply a secure sysadmin password>>
            EI.UseSQLSecurityMode = true;
            EI.AddUserAsAdmin = true;

            if (EI.InstallExpress())
                SetupDatabase();
        }

        private static void SetupDatabase()
        {
            string datafolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), CONFIG_FOLDER_NAME);
            try
            {
                SqlCommand cmd = new SqlCommand("select count(*) from sys.databases where name = 'MyVideoViewer'", conn);
                SqlCommand cmd2 = new SqlCommand(string.Format(Resources.CreateDatabase, datafolder), conn);

                if (!Directory.Exists(datafolder))
                    Directory.CreateDirectory(datafolder);

                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();
                int count = 0;
                count = (int)cmd.ExecuteScalar();

                if (count == 0)
                    cmd2.ExecuteNonQuery();

                if (conn.State == System.Data.ConnectionState.Open)
                    conn.Close();

                if (string.IsNullOrEmpty(connString))
                    throw new Exception("Connection string was not set");
                conn = new SqlConnection(connString);

                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                SqlCommand cmd3 = new SqlCommand(Resources.MyVideoViewer, conn);
                cmd3.ExecuteNonQuery();

                Console.WriteLine("My Video Viewer server was setup successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine("There was an error setting up the database:");
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (conn.State == System.Data.ConnectionState.Open)
                    conn.Close();
            }
            Finish();
        }

        private static bool CheckDatabaseConnection()
        {
            SqlCommand cmd = new SqlCommand("select count(*) from sys.databases", conn);
            try
            {
                
                int count = 0;
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();
                count = (int)cmd.ExecuteScalar();
                return true;                
            }
            catch 
            {
                if (conn.State == System.Data.ConnectionState.Open)
                    conn.Close();
                return false;                
            }
        }

        private static void Finish()
        {
            Console.WriteLine("Please press 'Enter' to continue.");
            Console.ReadLine();
        }
    }
}
